import { useState } from 'react'
import { useDispatch } from "react-redux"
import { useHistory } from 'react-router-dom'
import { Form, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { login } from '../apis/account'
import InputText from '../components/inputs/InputText'
import { queryCurUserAction } from "../store/actions/userActions"
import { queryAppDefinitionAction } from "../store/actions/appDefAction"
import logo2 from '../assets/logo2.png'

const Login = () => {

  const history = useHistory()
  const dispatch = useDispatch()

  const [sending, setSending] = useState(false)

  const onFinish = async (values) => {
    if (!sending) {
      setSending(true)
      try {
        const loginData = {
          ...values,
          _spring_security_remember_me: true,
          submit: 'login'
        }
        await login(loginData)
        message.success('登录成功！')
        dispatch(queryCurUserAction())
        dispatch(queryAppDefinitionAction())
        setSending(false)
        history.push('/')
      } catch (error) {
        setSending(false)
      }
    }
  };

  return <div className="login-wrap center-box">
    <div className="login-box">
      <img src={logo2} alt="logo" width="100%" className="login-logo" />
      <Form onFinish={onFinish} >
        <Form.Item
          name="j_username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <InputText
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="用户名"
          />
        </Form.Item>
        <Form.Item
          name="j_password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <InputText
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            autoComplete="new-password"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            block
            loading={sending}
            size="large"
          >登录</Button>
        </Form.Item>
      </Form>
    </div>
  </div>
}

export default Login